package org.wz.complex.work.impl.base;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wz.complex.work.anno.UniqueCol;
import org.wz.complex.work.kit.clz.FieldKit;
import org.wz.complex.work.service.base.BaseService;

import java.lang.reflect.Field;

public class BaseImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T>{

    @Override
    public void copyOne(Long id)  throws Exception {
        T t = this.getById(id);
        // class
        Field idFiled = t.getClass().getDeclaredField("id");
        idFiled.setAccessible(true);
        idFiled.set(t, null);
        //
        this.saveOrUpdate(t);
    }

    @Override
    public void copy2(Object one, Class<?> clz) {
        FieldKit.setValueByProperty(one, "id", null);
            // 设置唯一性约束的字段
        FieldKit.foreachAnnotation(UniqueCol.class, one, (field, anno) -> {
            Object value = FieldKit.getValue(field, one);
            if (null != value) {
                FieldKit.setValueByProperty(one, field.getName(), String.valueOf(value) + "__" + IdUtil.getSnowflakeNextIdStr());
            }
        });
//            // 保存
            save((T)one);
    }

}
